package com.aholu.validate;

import java.util.regex.Pattern;

import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.IValidator;
import org.apache.wicket.validation.ValidationError;

public class ValidateEmail implements IValidator<String> {

	private final String EMAIL_PATTERN = "(\\w+)(@)(\\w+)(.)(\\w+)";
	private final Pattern pattern;

	public ValidateEmail() {
		pattern = Pattern.compile(EMAIL_PATTERN);
	}

	public void validate(IValidatable<String> validatable) {

		final String email = validatable.getValue();

		if (pattern.matcher(email).matches() == false) {
			error(validatable, "Wrong email format");
		}

	}

	private void error(IValidatable<String> validatable, String errorKey) {
		ValidationError error = new ValidationError();
		error.addMessageKey(errorKey);
		validatable.error(error);
	}

}
